<template>
  <div>
    <div class="clearfix">
      <el-input
        v-model="url"
        :readonly="true"
        :placeholder="$t('请输入需要分享的链接地址')"
      />
    </div>
    <el-row>
      <el-button type="primary" @click="copyValue">{{ $t('复制') }}</el-button>
      <el-button plain @click="openPage">{{ $t('打开') }}</el-button>
      <el-button type="primary" @click="openPoster">
        {{ $t('制作二维码海报') }}
      </el-button>
    </el-row>
  </div>
</template>

<script>
export default {
  props: ['code'],

  data() {
    return {
      url: '',
      imgUrl: this.$store.getters.updateURL
    }
  },
  mounted() {
    if (!this.imgUrl) {
      var http = window.location.protocol // 获取协议
      var host = window.location.host // 获取主机名
      this.imgUrl = http + '//' + host + '/'
    }

    this.url = this.imgUrl + 'c/' + this.code
  },
  created() {},
  methods: {
    openPoster() {
      this.copyValue()
      this.$router.push({
        path: '/poster/index'
      })
    },
    openPage() {
      window.open(this.url)
    },
    // 先给要复制的文本或者按钮加上点击事件后，并将要复制的值传过来
    async copyValue() {
      const val = this.url
      if (navigator.clipboard && window.isSecureContext) {
        // navigator clipboard 向剪贴板写文本
        this.$message.success(this.$t('复制成功'))
        return navigator.clipboard.writeText(val)
      } else {
        // 创建text area
        const textArea = document.createElement('textarea')
        textArea.value = val
        // 使text area不在viewport，同时设置不可见
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        this.$message.success(this.$t('复制成功'))
        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand('copy') ? res() : rej()
          textArea.remove()
        })
      }
    }
  }
}
</script>

<style>
.clearfix {
  margin-bottom: 16px;
}
</style>
